//
//  TSQRCodeScanViewController.m
//  Drink5_User
//
//  Created by 李佳育 on 16/6/7.
//  Copyright © 2016年 Toocms. All rights reserved.
//

#import "TSQRCodeScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#define boxWidth 200
#define boxHeight 200
@interface TSQRCodeScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>
// <UITableViewDataSource,UITableViewDelegate>
//@property (nonatomic,   weak) UITableView * tableView;
//扫描二维码
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

@end

@implementation TSQRCodeScanViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self _initView];
    [self _initNavigationBar];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.session = nil;
    [self.previewLayer removeFromSuperlayer];
    self.previewLayer = nil;
}

-(void)viewDidDisappear:(BOOL)animated{
    self.session = nil;
    [self.previewLayer removeFromSuperlayer];
    self.previewLayer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self _initView];
    
//    [self _initNavigationBar];
}

#pragma mark - 初始化UI

/** 初始化View*/
- (void)_initView {
    [self ScanTheQRCode];
}

/** 初始化NavigaitonBar */
- (void)_initNavigationBar {
    WeakSelf;
    self.ts_navgationBar = [[TSNavigationBar alloc] initWithTitle:@"二维码扫描" backAction:^{
        [wself dismissViewControllerAnimated:YES completion:nil];
    }];
//    self.ts_navgationBar.backgroundColor = navigationBarColor;
}

#pragma mark - Action
-(void)btnClickHome_QRCodeScan:(UIButton *)sender{
    switch (sender.tag) {
        case 300:
            [self.previewLayer removeFromSuperlayer];
            self.tabBarController.tabBar.hidden = NO;
            break;
        default:
            break;
    }
}



#pragma mark - Delegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{

    
    if (metadataObjects.count > 0) {
        [self.session stopRunning];

        //获取数据
        AVMetadataMachineReadableCodeObject *obj = metadataObjects.firstObject;
        TSLog([obj stringValue]);
        NSString *str = [obj stringValue];
        
        // 创建弹框控制器
        UIAlertController *alertCtry=[UIAlertController alertControllerWithTitle:@"扫描结果" message:str preferredStyle:UIAlertControllerStyleAlert];
        //弹框的具体内容及响应事件
        UIAlertAction *addAction=[UIAlertAction actionWithTitle:@"知道啦" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:^{
                if ([self.delegate respondsToSelector:@selector(QRCodeResult:)]) {
                    [self.delegate QRCodeResult:str];
                }
            }];
        }];
        [alertCtry addAction:addAction];
        //把alertCtry 弹框视图推出来
        [self presentViewController:alertCtry animated:YES completion:nil];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 0;
}



-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * ID = @"<#String#>";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        
        cell = [[[NSBundle mainBundle] loadNibNamed:@"<#String#>" owner:self options:nil] lastObject];
    }
    
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    
//}

#pragma mark - Private
-(void)ScanTheQRCode{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    //权限
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted || authorizationStatus == AVAuthorizationStatusDenied) {
        [TSGlobalTool alertWithTitle:@"" message:@"摄像头访问权限受限" cancelButtonTitle:@"取消" OtherButtonsArray:nil clickAtIndex:^(NSInteger buttonIndex) {
            
        }];
        return;
    }
    
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (error) {
        TSLog(error);
        return;
    }
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    self.session = [[AVCaptureSession alloc] init];
    [self.session addInput:deviceInput];
    [self.session addOutput:output];
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.frame = [UIScreen mainScreen].bounds;
    [self.view.layer addSublayer:self.previewLayer];
    //扫描框
    UIView *boxView = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2, (kScreenHeigth - 64 - boxHeight) / 2, boxWidth, boxHeight)];
//    boxView.layer.borderColor = RGBColor(44, 130, 223).CGColor;
    boxView.layer.borderColor = RGBColor(250, 250, 250).CGColor;
    boxView.layer.borderWidth = 0.5;
    //四个角
    UIView *leftTopView_1 = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2, (kScreenHeigth - 64 - boxHeight) / 2, 5, 20)];
    leftTopView_1.backgroundColor = RGBColor(44, 130, 223);
    
    UIView *leftTopView_2 = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2, (kScreenHeigth - 64 - boxHeight) / 2, 20, 5)];
    leftTopView_2.backgroundColor = RGBColor(44, 130, 223);
    
    UIView *rightTopView_1 = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2 + boxWidth - 5, (kScreenHeigth - 64 - boxHeight) / 2, 5, 20)];
    rightTopView_1.backgroundColor = RGBColor(44, 130, 223);
    
    UIView *rightTopView_2 = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2 + boxWidth - 20, (kScreenHeigth - 64 - boxHeight) / 2, 20, 5)];
    rightTopView_2.backgroundColor = RGBColor(44, 130, 223);
    
    UIView *leftBootom_1 = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2, (kScreenHeigth - 64 - boxHeight) / 2 + boxHeight - 20, 5, 20)];
    leftBootom_1.backgroundColor = RGBColor(44, 130, 223);
    
    UIView *leftBootom_2 = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2, (kScreenHeigth - 64 - boxHeight) / 2 + boxHeight - 5, 20, 5)];
    leftBootom_2.backgroundColor = RGBColor(44, 130, 223);
    
    UIView *rightBootom_1 = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2 + boxWidth - 5, (kScreenHeigth - 64 - boxHeight) / 2 + boxHeight - 20, 5, 20)];
    rightBootom_1.backgroundColor = RGBColor(44, 130, 223);
    
    UIView *rightBootom_2 = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - boxWidth) / 2 + boxWidth - 20, (kScreenHeigth - 64 - boxHeight) / 2 + boxHeight - 5, 20, 5)];
    rightBootom_2.backgroundColor = RGBColor(44, 130, 223);
    
    [self.view addSubview:leftTopView_1];
    [self.view addSubview:leftTopView_2];
    [self.view addSubview:rightTopView_1];
    [self.view addSubview:rightTopView_2];
    [self.view addSubview:leftBootom_1];
    [self.view addSubview:leftBootom_2];
    [self.view addSubview:rightBootom_1];
    [self.view addSubview:rightBootom_2];
    //扫描区域
    [output setRectOfInterest:CGRectMake(0.1, 0.1, boxWidth * 2 / kScreenHeigth, boxHeight * 2 / kScreenWidth)];
    // 设置扫描线
    UIView *scanView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, boxWidth - 30, 2)];
    scanView.alpha = 0.2;
    scanView.backgroundColor = RGBColor(44, 130, 223);
    [boxView addSubview:scanView];
    [self.view addSubview:boxView];
    
    [self.session startRunning];
    [UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionRepeat animations:^{
        CGRect frame = scanView.frame;
        frame = CGRectMake(15, boxHeight - 4, boxWidth - 30, 4);
        scanView.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
}
#pragma mark - 懒加载



@end
